package com.xinghai.system.service.impl;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import com.xinghai.common.utils.DateUtils;

import com.xinghai.system.domain.*;
import com.xinghai.system.mapper.QdDealInfoMapper;
import com.xinghai.system.service.*;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import com.xinghai.common.constant.GenConstants;
import com.xinghai.system.mapper.QdPayOrderInfoMapper;

/**
 * 对账单明细Service业务层处理
 *
 * @author xinghai
 * @date 2024-12-07
 */
@Service
public class QdPayOrderInfoServiceImpl extends ServiceImpl<QdPayOrderInfoMapper, QdPayOrderInfo>
        implements IQdPayOrderInfoService
{

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Autowired
    private QdDealInfoMapper qdDealInfoMapper;

    @Autowired
    private IQdOrderService orderService;

    @Autowired
    private IQdUserWalletService walletService;

    @Autowired
    private IQdUserService userService;

    @Autowired
    private IQdUserWalletLogService walletLogService;
    /**
     * 查询对账单明细列表
     *
     * @param qdPayOrderInfo 对账单明细
     * @return 对账单明细集合
     */
    @Override
    public List<QdPayOrderInfo> list(QdPayOrderInfo qdPayOrderInfo) {
        QueryWrapper<QdPayOrderInfo> queryWrapper = new QueryWrapper<>();
        if (qdPayOrderInfo.getStatus()!= null  && !qdPayOrderInfo.getStatus().isEmpty()){
            queryWrapper.eq("status", qdPayOrderInfo.getStatus());
        }
        if (qdPayOrderInfo.getParams().get("beginCreateTime")!= null && !"".equals(qdPayOrderInfo.getParams().get("beginCreateTime"))
        &&qdPayOrderInfo.getParams().get("endCreateTime")!= null && !"".equals(qdPayOrderInfo.getParams().get("endCreateTime"))){
            queryWrapper.between("create_time", qdPayOrderInfo.getParams().get("beginCreateTime"),qdPayOrderInfo.getParams().get("endCreateTime"));
        }
        if (qdPayOrderInfo.getUserId()!= null ){
            queryWrapper.eq("user_id", qdPayOrderInfo.getUserId());
        }
        if (qdPayOrderInfo.getUserPhone()!= null  && !qdPayOrderInfo.getUserPhone().isEmpty()){
            queryWrapper.like("user_phone", qdPayOrderInfo.getUserPhone());
        }
        if (qdPayOrderInfo.getUserName()!= null  && !qdPayOrderInfo.getUserName().isEmpty()){
            queryWrapper.like("user_name", qdPayOrderInfo.getUserName());
        }
        if (qdPayOrderInfo.getStoreId()!= null ){
            queryWrapper.eq("store_id", qdPayOrderInfo.getStoreId());
        }
        if (qdPayOrderInfo.getStoreName()!= null  && !qdPayOrderInfo.getStoreName().isEmpty()){
            queryWrapper.like("store_name", qdPayOrderInfo.getStoreName());
        }
        if (qdPayOrderInfo.getLinkPayOrder()!= null ){
            queryWrapper.eq("link_pay_order", qdPayOrderInfo.getLinkPayOrder());
        }
        return this.list(queryWrapper);
    }

    /**
     * 删除对账单明细信息
     * @param id 需要删除的数据ID
     * @param flag 是否是逻辑删除
     * @return 结果
     */
    @Override
    public boolean delete(Long id, boolean flag) {
        if (flag){
            QdPayOrderInfo qdPayOrderInfo = new QdPayOrderInfo();
            qdPayOrderInfo.setId(id);
            qdPayOrderInfo.setDelFlag(GenConstants.DELETE_FLAG_YES);
            return this.updateById(qdPayOrderInfo);
        }
        return this.removeById(id);
    }

    /**
     * 批量删除对账单明细信息
     *
     * @param ids 需要删除的数据ID集合
     * @param flag 是否是逻辑删除
     * @return 结果
     */
    @Override
    @Transactional
    public boolean deleteBatch(Long[] ids, boolean flag) {
        if (flag){
            List<QdPayOrderInfo> collect = Arrays.stream(ids).map(m -> {
                QdPayOrderInfo qdPayOrderInfo = new QdPayOrderInfo();
                qdPayOrderInfo.setId(m);
                qdPayOrderInfo.setDelFlag(GenConstants.DELETE_FLAG_YES);
                return qdPayOrderInfo;
            }).collect(Collectors.toList());
            return this.updateBatchById(collect);
        }
        return this.removeByIds(Arrays.asList(ids));
    }

    /**
     * 导入对账单明细信息
     *
     * @param list 对账单明细信息集合
     * @return 结果
     */
    @Override
    @Transactional
    public boolean importData(List<QdPayOrderInfo> list){
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        try {
            QdPayOrderInfoMapper qdPayOrderInfoMapper = sqlSession.getMapper(QdPayOrderInfoMapper.class);
            list.forEach(qdPayOrderInfoMapper::insert);
            // 提交数据
            sqlSession.commit();
            sqlSession.rollback();
        } catch (Exception e) {
            sqlSession.rollback();
            return false;
        } finally {
            sqlSession.close();
        }
        return true;
    }

    @Override
    public QdPayOrderInfo getByPayOrderId(String payOrderId,String loginId) {
        if (payOrderId != null){
            QueryWrapper<QdPayOrderInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("link_pay_order", payOrderId);
            queryWrapper.eq("user_id", loginId);
            QdPayOrderInfo info = this.getOne(queryWrapper);
            if (info != null){
                QueryWrapper<QdDealInfo> dealInfoQueryWrapper = new QueryWrapper<>();
                dealInfoQueryWrapper.eq("order_info_id", info.getId());
                List<QdDealInfo> dealInfoList = qdDealInfoMapper.selectList(dealInfoQueryWrapper);
                info.setDealInfoList(dealInfoList);
                return info;
            }
        }
        return null;
    }


    @Override
    public QdPayOrderInfo getByDataId(String dataId) {
        if (dataId != null){
            QdPayOrderInfo info = this.getById(dataId);
            if (info != null){
                QueryWrapper<QdDealInfo> dealInfoQueryWrapper = new QueryWrapper<>();
                dealInfoQueryWrapper.eq("order_info_id", info.getId());
                List<QdDealInfo> dealInfoList = qdDealInfoMapper.selectList(dealInfoQueryWrapper);
                info.setDealInfoList(dealInfoList);
                return info;
            }
        }
        return null;
    }

    @Override
    @Transactional
    public boolean confirmBalance(QdPayOrderInfo info) {
        info.setStatus("1");
        //给所有订单的会员上级返佣金
        QdOrder order = new QdOrder();
        order.setBuyerUserId(info.getUserId());
        order.setBuyerStatus("1");
        QdUser user = userService.getById(info.getUserId());
//        QdUserWallet wallet1;
//        if (user.getSuperId()!=null){
//            wallet1 = walletService.getByUserId(String.valueOf(user.getSuperId()));
//        } else {
//            wallet1 = null;
//        }
        List<QdOrder> list = orderService.list(order);
        //QdUserWallet wallet = walletService.getByUserId(String.valueOf(info.getUserId()));
        //List<QdUserWalletLog> logs = new ArrayList<>();
        list.forEach(m->{
            m.setBuyerStatus("2");
            m.setSellerStatus("2");
//            wallet.setListingFee(wallet.getListingFee().add(m.getListingFee()));
//            wallet.setPurchaseAmount(wallet.getPurchaseAmount().add(m.getPrice()));//买入
//            wallet.setNowMoney(wallet.getNowMoney().add(m.getPrice()));
//            wallet.setNowOrderNum(wallet.getNowOrderNum()+1);
            //然后分佣金
//            if (wallet1 != null){
//                wallet1.setAllWallet(wallet1.getAllWallet().add(m.getPushAmount()));
//                wallet1.setWithdrawalWallet(wallet1.getWithdrawalWallet().add(m.getPushAmount()));
//                //插入日志
//                QdUserWalletLog qdUserWalletLog = new QdUserWalletLog();
//                qdUserWalletLog.setUserId(user.getSuperId());
//                qdUserWalletLog.setUserPhone(user.getSuperUserPhone());
//                qdUserWalletLog.setChangeAmount(m.getPushAmount());
//                qdUserWalletLog.setType("1");
//                qdUserWalletLog.setDetail(String.format("来自【%s】的佣金",m.getBuyerUserName()));
//                logs.add(qdUserWalletLog);
//            }
        });
        //241217 自己卖的单子，不上架
//        QdOrder order1 = new QdOrder();
//        order1.setSellerUserId(info.getUserId());
//        order1.setSellerStatus("1");
//        List<QdOrder> list11 = orderService.list(order1);
//        list11.forEach(m->{
//            m.setSellerStatus("2");
//            m.setBuyerStatus("2");
//            //wallet.setAchievement(wallet.getAchievement().add(m.getPrice()));//卖出
//        });
        //walletService.updateById(wallet);
//        if (!list11.isEmpty()){
//            orderService.updateBatchById(list11);
//        }


        if (!list.isEmpty()){
            //更新订单为待上架
            orderService.updateBatchById(list);
            user.setDealDay(user.getDealDay()+1);
            userService.updateById(user);
//            if (wallet1 != null){
//                walletService.updateById(wallet1);
//                if (!logs.isEmpty()){
//                    walletLogService.saveBatch(logs);
//                }
//            }
        }
        return this.updateById(info);
    }
}
